<?php
namespace app\exception;

use think\exception\Handle;
use think\exception\HttpException;
use think\Response;
use think\Log;


class Http extends Handle
{
  /**
   * 异常处理函数 
   * 重写 Handle 的render函数
   *
   * @param \Exception $e 异常类
   * @return void
   */
  public function render(\Exception $e)
  {
    if (!$e instanceof HttpException) {
      return $this->serverError($e);
    } else {
      return $this->httpError($e);
    }
  }

  /**
   * 服务器内部错误
   *
   * @return void
   */
  public function serverError(\Exception $e)
  {
    $data = [
      'file' => $e->getFile(),
      'line' => $e->getLine(),
      'message' => $e->getMessage(),
      'code' => $e->getCode(),
    ];
    $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]";
    $module = strstr(ltrim(strstr(strstr($data['file'], 'application'), '\\'), '\\'), '\\', true);
    $this->log($log, $module, 'error');
    return Response::create('服务器错误', 'json', 500);
  }

  /**
   * 客户端请求错误
   *
   * @param HttpException $e http请求异常
   * @return void
   */
  public function httpError(HttpException $e)
  {

    $status = $e->getStatusCode();
    $msg = $e->getMessage();
    $module = 'http';
    $log = $status . ' ' . $msg;
    $this->log($log, $module, 'error');
    if ($status === 404) {
      return Response::create('参数错误', 'json', $status);
    } else {
      return Response::create($msg, 'json', $status);
    }
  }


  /**
   * 保存日志
   *
   * @param mixed $log
   * @return void
   */
  protected function log($log, $module, $level)
  {
    Log::init([
      'type' => 'SeaLog',
      'path' => LOG_PATH,
      'module' => $module
    ]);
    Log::record($log, $level);
  }
}